package utils

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"sync"
)

var mutex = sync.Mutex{}

func WxRequest(url string, conf *map[string]interface{}, en_cookie bool) []byte {
	wxReq, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("网络请求出现错误: ", err)
		fmt.Println(url)
		os.Exit(-1)
	}
	wxReq.Header = http.Header{}
	wxReq.Header.Add("authority", "mp.weixin.qq.com")
	wxReq.Header.Add("scheme", "https")
	wxReq.Header.Add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
	wxReq.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.884.400 QQBrowser/9.0.2524.400")

	cookies := (*conf)["cookies"].(map[string]string)

	if en_cookie {
		for k, v := range cookies {
			cookie := &http.Cookie{}
			cookie.Name = k
			cookie.Value = v
			cookie.Path = "/"
			cookie.HttpOnly = true
			wxReq.AddCookie(cookie)
		}
	}
	response, err := http.DefaultClient.Do(wxReq)
	if err != nil {
		fmt.Println("网络请求出现错误: ", err)
		return []byte{}
	}
	if en_cookie {
		for key, value := range response.Header {
			if key == "Set-Cookie" {
				// 修改cookie的操作需要同步
				mutex.Lock()
				for _, str := range value {
					fmt.Println("cookie:", str)
					//fmt.Println(str)
					index := strings.Index(str, "=")
					indey := strings.Index(str, "; ")
					//给全局配置的cookie也设置一下，后续逐渐用全局cookie替换局部的
					cookies[str[0:index]] = str[index+1 : indey]
				}
				mutex.Unlock()
			}
		}
	}
	respByte, _ := io.ReadAll(response.Body)
	response.Body.Close()
	return respByte
}
